#!/usr/bin/env python

import sys, getopt
import syscons


def usage():
    print "Usage: convert_screenmap [-i fonts_codepage] [-o output_screenmap]"


if __name__ == "__main__":

    # parse command options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:o:h", ["help", ])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)

    if len(args) > 0:
        usage()
        sys.exit(2)

    input_codepage_file = None
    output_screenmap_file = None

    for o, a in opts:
        if o == '-h' or o == '--help':
            usage()
            sys.exit(0)
        elif o == "-i":
            input_codepage_file = a
        elif o == "-o":
            output_screenmap_file = a
        else:
            assert False, 'unhandled option'


    unicodemap = syscons.UnicodeMap()

    # read and parse codepage file
    if input_codepage_file:
        icf = open(input_codepage_file, "r")
    else:
        icf = sys.stdin

    try:
        linenum = 0
        for line in icf:
            linenum += 1

            try:
                unicodemap.addEntry(line)
            except ValueError, err:
                print >> sys.stderr, 'Error in line {0:d}'.format(linenum)
    finally:
        if icf is not sys.stdin:
            icf.close()


    if output_screenmap_file:
        osf = open(output_screenmap_file, "w")
    else:
        osf = sys.stdout

    oformat = '{{ {0:#06x}, {1:#04x}, {2:#04x} }},\n'
    try:
        prevunicode, prevcode, prevcount = None, None, 0
        for u in unicodemap.sortedByUnicode():
            if u.code < 32 or u.code == 127:
                continue
            if prevunicode is None or prevcode is None:
                prevunicode, prevcode, prevcount = u.unicode, u.code, 1
            elif prevunicode + prevcount == u.unicode and prevcode + prevcount == u.code:
                prevcount = prevcount + 1
            else:
                osf.write(oformat.format(prevunicode, prevcode, prevcount - 1))
                prevunicode, prevcode, prevcount = u.unicode, u.code, 1
        if prevunicode is not None and prevcode is not None:
            osf.write(oformat.format(prevunicode, prevcode, prevcount - 1))
    finally:
        if osf is not sys.stdin:
            osf.close()

    sys.exit(0)
